package com.yhy;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ReferenceCounted;

public class MyChannelInboundHandler2 extends ChannelInboundHandlerAdapter{
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //处理消息
        ByteBuf result = (ByteBuf)msg;
        byte[] content = new byte[result.readableBytes()];
        result.readBytes(content);

        String resultStr = new String( content );
        System.out.println(getClass().getSimpleName() + "." + "hand2 channelRead: " + resultStr + ctx.channel().remoteAddress());

        //不执行会此行用 JProfiler 分析，会有netty 内存池 PoolSubpage 内存泄露
        result.release();
//        ReferenceCountUtil.release(result);     //这句和上面效果一致


        //返回消息
        ChannelFuture future = ctx.channel().write("recvied message\n");
        //等待发送成功的通知。
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                System.out.println("future: MyChannelInboundHandler2 收到 write() 成功的消息");
            }
        });
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(getClass().getSimpleName() + "." + "hand2 channelActive:" + ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(getClass().getSimpleName() + "." + "hand2 channelInactive:" + ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println(getClass().getSimpleName() + "." + "hand2 exceptionCaught:" + cause + ctx.channel().remoteAddress());
    }
}
